package org.example.judge_admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.judge_admin.mapper.AuthMapper;
import org.example.judge_admin.service.AuthService;
import org.example.judge_admin.service.UserAuthService;
import org.example.judge_common.util.IdWorker;
import org.example.judge_common.util.MyUtils;
import org.example.judge_pojo.Auth;
import org.example.judge_pojo.UserAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("AuthServiceImpl")
@Transactional
public class AuthServiceImpl extends ServiceImpl<AuthMapper, Auth> implements AuthService {

    @Autowired
    private IdWorker idWorker;
    @Qualifier("UserAuthServiceImpl")
    @Autowired
    private UserAuthService userAuthService;

    /**
     *
     * @param userId
     * @param status status==2 zhi要系统保留权限
     * @param isDelete 是否剔除保留权限，true剔除 三个系统保留权限
     * @return
     */
    @Override
    public List<Auth> listByUserId(String userId,Integer status,boolean isDelete) {
        if(status!=null&&status!=2&&isDelete)status = null;
        List<Auth> auths = this.baseMapper.getAuthsByUserId(userId, status);
        if(!isDelete)return auths;
        //重构
        List<Auth> res = new ArrayList<>();
        // 获取保留权限

        if(status!=null&&status==2){
            for (Auth auth : auths) {
                if(Auth.isKeep(auth.getCode())){  //只要系统保留
                    res.add(auth);
                }
            }
        }else{
            for (Auth auth : auths) {
                if(!Auth.isKeep(auth.getCode())){  //不要系统保留
                    res.add(auth);
                }
            }
        }

        return res;
    }

    @Override
    public Auth getAuthByCode(String client) {
        QueryWrapper<Auth> query = new QueryWrapper<>();
        query.eq("code",client);
        Auth one = this.getOne(query);
        return one;
    }

    @Override
    public boolean removeById(Serializable id) {
        userAuthService.removeByAuthId(id);
        return super.removeById(id);
    }

    @Override
    public boolean save(Auth entity) {
        entity.setId(idWorker.nextId().toString());
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
//        System.out.println(entity);
        if(entity.getStatus()==null)entity.setStatus(0);
        return super.save(entity);
    }
}
